package com.zj003.module.sys.service.impl;

import com.zj003.common.domain.entity.SysUser;
import com.zj003.common.domain.model.LoginUser;
import com.zj003.module.sys.mapper.SysUserMapper;
import com.zj003.module.sys.service.SysPermissionService;
import com.zj003.module.sys.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsPasswordService;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Set;

/**
 * @author RedName
 * @description 针对表【sys_user(用户信息表)】的数据库操作Service实现
 * @createDate 2022-05-01 03:30:07
 */
@Service
@RequiredArgsConstructor
public class SysUserServiceImpl implements SysUserService, UserDetailsService, UserDetailsPasswordService {

    private final SysUserMapper userMapper;

    private final SysPermissionService permissionService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser user = userMapper.selectByUserName(username).<UsernameNotFoundException>orElseThrow(() -> {
            throw new UsernameNotFoundException("未找到用户名为".concat(username).concat("的用户"));
        });
        Set<String> menuPermission = permissionService.getMenuPermission(user.getUserId());
        String[] menu = menuPermission.stream().map("ROLE_"::concat).toArray(String[]::new);

        return new LoginUser(user, AuthorityUtils.createAuthorityList(menu));

    }

    @Override
    public UserDetails updatePassword(UserDetails userDetails, String newPassword) {
        LoginUser loginUser = (LoginUser) userDetails;
        SysUser user = loginUser.getUser();
        SysUser newUser = user.withPassword(newPassword);
        userMapper.updatePasswordByUserName(newUser.getPassword(), newUser.getUserName());

        loginUser.setUser(newUser);

        return loginUser;
    }
}
